var _ = require('lodash'),
    Q = require('q'),
    mongoose = require('mongoose'),
    PublicEnum = require('../../../Base/server/controllers/Enum'),
    Transaction = require('../../../Base/server/controllers/Transaction'),
    entityCollection = require('../../../Base/server/controllers/EntityCollection'),
    barcodeMasterController = require('../../../Barcode/server/controllers/BarcodeMaster.server.controller'),
    operationController = require('../../../CBO/server/controllers/Operation.server.controller'),
    kanbanDemandController = require('../../../ProduceWork/server/controllers/KanbanDemand.server.controller'),
    rcvRecordController = require('../../../ProduceWork/server/controllers/RcvRecord.server.controller'),
    connectAreaController = require('../../../CBO/server/controllers/WareHouse.server.controller'),
    departmentController = require('../../../CBO/server/controllers/Department.server.controller'),
    terminalController = require('../../../CBO/server/controllers/Terminal.server.controller'),
    DeliveryRecordController = require('../../../ProduceWork/server/controllers/DeliveryRecord.server.controller'),
    bizRecordController = require('../../../Barcode/server/controllers/BizRecord.server.controller'),
    MOController = require('../../../ProduceReady/server/controllers/MO.server.contorller'),
    wareHouseController = require('../../../CBO/server/controllers/WareHouse.server.controller'),
// SocketIo = require('../../../Base/server/controllers/Socket'),
    ContainerController = require('../../../CBO/server/controllers/Container.server.controller');


exports.createKanban = function (req, res) {
    var parameter = req.body.Parameter,
        barcode = parameter.Barcode,
        userId = req.user._id;

    checkKanbanExist(barcode).then(function (result) {
        return Q.when(result.exist ? result.MO : createKanbanRecords(result.MO, userId));
    }).then(function (results) {
        res.json({
            Data: true,
            Error: null
        });
    }).catch(function (err) {
        res.json({
            Data: null,
            Error: err
        });
    })
        .done();
};

function checkKanbanExist(barcode) {
    var deferred = Q.defer();

    barcodeMasterController.findBarcodeMaster(barcode, function (err, barcodeMaster) {
        if (err) {
            deferred.reject(err);
            return;
        }
        if (!barcodeMaster || barcodeMaster.BarcodeType != 0) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询物料错误';
            newErr.message = '无法识别的芯片，请重新扫描！';
            deferred.reject(newErr);
            return;
        }
        kanbanDemandController.findOneByMoId(barcodeMaster.MO, function (err, demands) {
            if (err) {
                deferred.reject(err);
                return;
            }
            deferred.resolve({
                exist: demands ? true : false,
                MO: barcodeMaster.MO
            });
        });
    });

    return deferred.promise;
}

function createKanbanRecords(Mo, userId) {
    var deferred = Q.defer();

    connectAreaController.distinctId(function (err, areaIds) {
        if (err) {
            deferred.reject(err);
            return;
        }
        var kanbanDemandRecords = [];
        _.forEach(areaIds, function (areaId) {
            kanbanDemandRecords.push({
                RowStatus: PublicEnum.RowStatus.Insert,
                CreatedBy: userId,
                MO: Mo,
                ConnectArea: areaId
            });
        });
        Transaction.BatchSaveByTran([
                {EntityName: 'KanbanDemand', Records: kanbanDemandRecords}
            ],
            function (err, result) {
                if (err) {
                    deferred.reject(err);
                    return;
                }
                deferred.resolve(result);
            }
        );
    });

    return deferred.promise;
}

//通过终端获取交接区
exports.queryConnectAreaByTerminal = function (req, res) {
    var parameter = req.body.Parameter,
        uniqueID = parameter.uniqueID,
        isUp = true;
    if (parameter.isUp) {
        isUp = parameter.isUp;
    }
    terminalController.findByUniqueID(uniqueID, function (err, record) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
            return;
        }
        if (record._id) {
            var entity = entityCollection.getEntity("StationTerminal");
            entity.findOne({Terminal: record._id}, [{
                    path: 'WorkLocation',
                    select: 'Department'
                }],
                function (err, result) {
                    if (err) {
                        res.json({
                            Data: null,
                            Error: err
                        });
                    } else {
                        var queryCondition;
                        if (isUp) {
                            queryCondition = {UpDepartment: result.WorkLocation.Department};
                        } else {
                            queryCondition = {DownDepartment: record.WorkLocation.Department};
                        }
                        //通过用户部门获取交界区
                        connectAreaController.getConnectAreaByDepartment(queryCondition, function (err, connectAreaResult) {
                            if (err) {
                                res.json({
                                    Data: null,
                                    Error: err
                                });
                            } else {
                                res.json({
                                    Data: connectAreaResult,
                                    Error: null
                                });
                            }
                        });
                    }
                });
        } else {
            res.json({
                Data: null,
                Error: "通过终端UUID未查询到相关设备。"
            });
        }
    });
};

//通过作业获取待转区
exports.queryTransferAreaByWork = function (req, res) {
    var parameter = req.body.Parameter,
        workId = parameter.workId,
        isUp = parameter.isUp;

    var queryCondition;
    if (isUp) {
        queryCondition = {InputWork: workId};
    } else {
        queryCondition = {TargetWork: workId};
    }
    connectAreaController.getWareHouseInfo(queryCondition, function (err, wareHouseInfo) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            if (wareHouseInfo == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询待转区失败';
                newErr.message = '未找到对应的待转区！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            } else {
                res.json({
                    Data: wareHouseInfo,
                    Error: null
                });
            }

        }
    });
};

//看板id不为空（更新数据，提交本次要货量添加到累计要货量中）
//看板id为空  （添加数据）
exports.submitDemandQty = function (req, res) {
    var parameter = req.body.Parameter,
        userId = parameter.userId,
        submitData = parameter.submitData;

    //更新累计要货字段的数量
    // var promises = [];


    // submitData.forEach(function (data) {
    //     promises.push(
    //     kanbanDemandController.updateByValue(data.KanbanId, {TotalDemandQty: data.TotalDemandQty+data.DemandQty}, function (err, result) {
    //         if (err) {
    //             res.json({
    //                 Data: null,
    //                 Error: err
    //             });
    //         }
    //         else {
    //             if (result.ok === 1) {
    //                 res.json({
    //                     Data: true,
    //                     Error: null
    //                 });
    //             }
    //         }

    //     })); 
    // });

    // Q.all(promises).then(function () {
    //     res.json({
    //        Data: moDatas,
    //        Error: null
    //     });
    // });
    var updateDatas = [];
    var addDatas = [];
    for (var i = 0; i < submitData.length; i++) {
        var data = submitData[i];
        if (data.KanbanId) {
            updateDatas.push({
                _id: data.KanbanId,
                TotalDemandQty: data.TotalDemandQty + data.DemandQty
            });
        } else {
            addDatas.push({
                ItemMaster: data.ItemMaster,
                DescSeg1: data.DescSeg1,
                DescSeg2: data.DescSeg2,
                WareHouse: data.WareHouse,
                TotalDemandQty: data.DemandQty,
                TotalStockQty: 0,
                TotalReceiveQty: 0,
                DemandDepartment: data.DemandDepartment
            });
        }

    }

    updateDatas.forEach(function (data) {
        data.RowStatus = PublicEnum.RowStatus.Modify;
        data.ModifyBy = data._id;
    });

    updateKanbanDemands(updateDatas).then(function (result) {
        addDatas.forEach(function (data) {
            data.RowStatus = PublicEnum.RowStatus.Insert;
            data.CreatedBy = userId;
        });
        addKanbanDatas(addDatas).then(function (result) {
            console.log(result);
            res.json({
                Data: result,
                Error: null
            });
        }, function (err) {
            console.log(err);
            res.json({
                Data: null,
                Error: err
            });

        });

    }, function (err) {
        console.log(err);
        res.json({
            Data: null,
            Error: err
        });

    });

};

function updateKanbanDemands(KanbanDemands) {
    var deferred = Q.defer();
    Transaction.BatchSaveByTran([
            {EntityName: 'KanbanDemand', Records: KanbanDemands}
        ],
        function (err, result) {
            if (err) {
                deferred.reject(err);
                return;
            }
            deferred.resolve(result);
        }
    );
    return deferred.promise;
}

function addKanbanDatas(KanbanDatas) {
    var deferred = Q.defer();
    Transaction.BatchSaveByTran([
            {EntityName: 'KanbanDemand', Records: KanbanDatas}
        ],
        function (err, result) {
            if (err) {
                deferred.reject(err);
                return;
            }
            deferred.resolve(result);
        }
    );
    return deferred.promise;
}


//获取看板的数据
exports.queryKanbanData = function (req, res) {
    var parameter = req.body.Parameter,
        flag = parameter.flag,
        departmentId = parameter.departmentId,
        wareHouseId = parameter.wareHouseId;

    //在入库记录表中找到对应待转区的入库数据    
    rcvRecordController.queryByContainerAndWareHouse(wareHouseId, function (err, rcvRecords) {

        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            if (rcvRecords == null || rcvRecords.length === 0) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询入库记录失败';
                newErr.message = '未找到对应的入库记录！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            } else {
                // console.log(rcvRecords);
                //入库记录表中同一仓库数据进行分组（物料+尺寸+外观）
                // var entity = entityCollection.getEntity("RcvRecord");
                // var barcodeMap = function () {
                //     // emit(this.BarcodeMaster.ItemMasterCode, {WorkLocations: [this.WorkLocation]});
                //     // emit(this.RcvQty, this.BarcodeMaster);
                //     emit(this.BarcodeMaster.ItemMasterCode, this.BarcodeMaster);
                // };
                // var barcodeReduce = function (key, values) {
                //     // var res = {WorkLocations: []};
                //     // values.forEach(function (val) {
                //     //     val.WorkLocations.forEach(function (WorkLocation) {
                //     //         res.WorkLocations.push(WorkLocation);
                //     //     });
                //     // });
                //     // return res;
                //     // var ret={RcvQty:key,BarcodeMasters:values};
                //     var ret={ItemMasterCode:key,BarcodeMasters:values};
                //     return ret;
                // };

                // // var barcodeQuery = {
                // //     WareHouse: wareHouseId,
                // //     Container: null
                // // };

                // var option = {
                //     map: barcodeMap,
                //     reduce: barcodeReduce,
                //     sort: {ItemMasterCode: -1},
                //     query: null
                // };

                // rcvRecords.mapReduce(option, function (err, results) {
                //     if (err) {
                //         return;
                //     }
                //     console.log(results);
                //     res.json({
                //         Data: results,
                //         Error: null
                //     });
                // });
                if (rcvRecords[0].BarcodeMaster != null) {

                    //找到不同的物料
                    var ItemMasters = [{
                        ItemMaster: rcvRecords[0].BarcodeMaster.ItemMaster,
                        ItemMasterCode: rcvRecords[0].BarcodeMaster.ItemMasterCode
                    }];
                    for (var i = 0; i < rcvRecords.length; i++) {
                        if (rcvRecords[i].BarcodeMaster === null) {
                            continue;
                        }
                        var repeat = false;
                        for (var j = 0; j < ItemMasters.length; j++) {
                            if (rcvRecords[i].BarcodeMaster.ItemMasterCode === ItemMasters[j].ItemMasterCode) {
                                repeat = true;
                                break;
                            }
                        }
                        if (!repeat) {
                            ItemMasters.push({
                                ItemMaster: rcvRecords[i].BarcodeMaster.ItemMaster,
                                ItemMasterCode: rcvRecords[i].BarcodeMaster.ItemMasterCode
                            });
                        }
                    }
                    //找到不同的尺寸
                    var DescSeg1s = [rcvRecords[0].BarcodeMaster.DescSeg1];
                    for (var i = 0; i < rcvRecords.length; i++) {
                        if (rcvRecords[i].BarcodeMaster === null) {
                            continue;
                        }
                        var repeat = false;
                        for (var j = 0; j < DescSeg1s.length; j++) {
                            if (rcvRecords[i].BarcodeMaster.DescSeg1 === DescSeg1s[j]) {
                                repeat = true;
                                break;
                            }
                        }

                        if (!repeat) {
                            DescSeg1s.push(rcvRecords[i].BarcodeMaster.DescSeg1);
                        }
                    }
                    //找到不同的外观
                    var DescSeg2s = [rcvRecords[0].BarcodeMaster.DescSeg2];
                    for (var i = 0; i < rcvRecords.length; i++) {
                        if (rcvRecords[i].BarcodeMaster === null) {
                            continue;
                        }
                        var repeat = false;
                        for (var j = 0; j < DescSeg2s.length; j++) {
                            if (rcvRecords[i].BarcodeMaster.DescSeg2 === DescSeg2s[j]) {
                                repeat = true;
                                break;
                            }
                        }

                        if (!repeat) {
                            DescSeg2s.push(rcvRecords[i].BarcodeMaster.DescSeg2);
                        }
                    }

                    //入库记录表中同一仓库数据进行分组（物料+尺寸+外观）
                    var items = [];
                    for (var i = 0; i < ItemMasters.length; i++) {
                        for (var j = 0; j < DescSeg1s.length; j++) {
                            for (var k = 0; k < DescSeg2s.length; k++) {
                                var num = 0;
                                for (var a = 0; a < rcvRecords.length; a++) {
                                    var temp = rcvRecords[a].BarcodeMaster;
                                    if (temp === null) {
                                        continue;
                                    }
                                    if (ItemMasters[i].ItemMasterCode === temp.ItemMasterCode && DescSeg1s[j] === temp.DescSeg1
                                        && DescSeg2s[k] === temp.DescSeg2) {
                                        num++;
                                    }
                                }
                                ;
                                if (num != 0) {
                                    items.push({
                                        ItemMasterCode: ItemMasters[i].ItemMasterCode,
                                        ItemMaster: ItemMasters[i].ItemMaster,
                                        DescSeg1: DescSeg1s[j],
                                        DescSeg2: DescSeg2s[k],
                                        Num: num
                                    });
                                }
                            }
                            ;
                        }
                        ;
                    }
                    ;

                    // console.log(ItemMasters);
                    // console.log(DescSeg1s);
                    // console.log(DescSeg2s);
                    // console.log(items);

                    //存入每个分类（物料+尺寸+外观）的信息
                    var promises = [];
                    var itemDatas = [];
                    items.forEach(function (item) {
                        if (flag === "down") {

                            promises.push(queryKanbanDemand(item, wareHouseId, departmentId, itemDatas));
                        }
                        else if (flag === "up") {

                            promises.push(queryGiveKanbanDemand(item, wareHouseId).then(function (result) {

                                itemDatas = itemDatas.concat(result);

                            }, function (error) {

                            }));
                        } else {

                        }

                    });

                    Q.all(promises).then(function () {

                        // console.log(itemDatas);
                        if (flag === "down") {
                            kanbanDemandController.findAllKanbanDemand(wareHouseId, departmentId, function (err, result) {

                                var resultDatas = [];
                                if (err) {
                                    res.json({
                                        Data: null,
                                        Error: err
                                    });
                                } else {
                                    if (result) {
                                        var a = 0;
                                        for (var i = 0; i < result.length; i++) {
                                            var item = result[i];
                                            a = 0;
                                            for (var j = 0; j < itemDatas.length; j++) {
                                                if (itemDatas[j].KanbanId) {
                                                    if (result[i]._id.toString() != itemDatas[j].KanbanId.toString()) {
                                                        a++;
                                                    }
                                                } else {
                                                    a++;
                                                }
                                            }
                                            if (a === itemDatas.length) {
                                                resultDatas.push({
                                                    KanbanId: item._id,
                                                    ItemMasterCode: item.ItemMaster.Code,
                                                    ItemMasterName: item.ItemMaster.Name,
                                                    DescSeg1: item.DescSeg1,
                                                    DescSeg2: item.DescSeg2,
                                                    RcvQty: 0,
                                                    TotalReceiveQty: item.TotalReceiveQty,
                                                    NeedDeliveryQty: item.TotalStockQty - item.TotalReceiveQty,
                                                    DemandQty: 0,
                                                    TotalDemandQty: item.TotalDemandQty,
                                                    DemandDepartment: item.DemandDepartment

                                                });
                                            }

                                        }
                                        //待创建的看板数据+看板中的数据
                                        // console.log(resultDatas);
                                        // console.log("---------------------------");
                                        // console.log(itemDatas);
                                        itemDatas = itemDatas.concat(resultDatas);

                                        res.json({
                                            Data: itemDatas,
                                            Error: null
                                        });
                                    }
                                    else {
                                        var newErr = new Error();
                                        newErr.leval = 9;
                                        newErr.title = '查询看板记录失败';
                                        newErr.message = '未找到对应的看板记录！';
                                        res.json({
                                            Data: null,
                                            Error: newErr
                                        });
                                    }
                                }
                            });
                        }
                        else if (flag === "up") {
                            res.json({
                                Data: itemDatas,
                                Error: null
                            });
                        }
                        else {

                        }

                    });

                } else {
                    res.json({
                        Data: null,
                        Error: "条码主档为空"
                    });
                }
            }
        }
    });
};


//通过（物料+尺寸+外观）和仓库id和部门id查询要货看板需求表中数据
function queryKanbanDemand(item, wareHouseId, departmentId, itemDatas) {
    var deferred = Q.defer();
    var data = {};
    kanbanDemandController.findOneKanbanDemand(item, wareHouseId, departmentId, function (err, result) {

        if (err) {
            deferred.reject(err);
        } else {
            if (result) {
                data = {
                    KanbanId: result._id,
                    ItemMasterCode: result.ItemMaster.Code,
                    ItemMasterName: result.ItemMaster.Name,
                    DescSeg1: item.DescSeg1,
                    DescSeg2: item.DescSeg2,
                    RcvQty: item.Num,
                    TotalReceiveQty: result.TotalReceiveQty,
                    // NeedDeliveryQty: result.TotalDemandQty - Math.max(result.TotalStockQty, result.TotalReceiveQty),
                    NeedDeliveryQty: result.TotalDemandQty - result.TotalReceiveQty,
                    // DemandQty: result.TotalDemandQty - result.TotalReceiveQty,
                    DemandQty: 0,
                    TotalDemandQty: result.TotalDemandQty,
                    DemandDepartment: result.DemandDepartment
                    // numberColor:false,//控制追加数字颜色
                    // minusDisable:true//控制能追加不能追减
                };
                itemDatas.push(data);
                deferred.resolve(itemDatas);
            }
            //在看板表中未找到的也要返回数据，等待创建
            else {
                data = {
                    KanbanId: null,
                    ItemMasterCode: item.ItemMasterCode,
                    ItemMaster: item.ItemMaster,
                    DescSeg1: item.DescSeg1,
                    DescSeg2: item.DescSeg2,
                    RcvQty: item.Num,
                    TotalReceiveQty: 0,
                    // NeedDeliveryQty: result.TotalDemandQty - Math.max(result.TotalStockQty, result.TotalReceiveQty),
                    NeedDeliveryQty: 0,
                    DemandQty: 0,
                    TotalDemandQty: 0

                };
                itemDatas.push(data);
                deferred.resolve(itemDatas);
            }
        }
    });
    return deferred.promise;
}


//通过（物料+尺寸+外观）和仓库id和部门id查询要货看板需求表中数据
// function queryKanbanDemand(item, wareHouseId,departmentId,itemDatas) {
//     var deferred = Q.defer();
//     var data = {};
//     kanbanDemandController.findOneKanbanDemand(item, wareHouseId,departmentId, function (err, result) {

//         if (err) {
//             // console.log(err);
//             deferred.reject(err);
//         } else {
//             // console.log(result);
//             //在看板表中未找到的也要返回数据，等待创建
//             if (result===null) {
//                 data = {
//                     KanbanId: null,
//                     ItemMasterCode: item.ItemMasterCode,
//                     ItemMaster: item.ItemMaster,
//                     DescSeg1: item.DescSeg1,
//                     DescSeg2: item.DescSeg2,
//                     RcvQty: item.Num,
//                     TotalReceiveQty: 0,
//                     // NeedDeliveryQty: result.TotalDemandQty - Math.max(result.TotalStockQty, result.TotalReceiveQty),
//                     NeedDeliveryQty: 0,
//                     DemandQty: 0,
//                     TotalDemandQty: 0

//                 };
//                 itemDatas.push(data)
//                 deferred.resolve(itemDatas);        
//             } 
//             else{
//                 deferred.resolve(itemDatas); 
//             }  
//         }
//     });
//     return deferred.promise;
// }

//通过（物料+尺寸+外观）和仓库id查询 备货看板需求表中数据
function queryGiveKanbanDemand(item, wareHouseId) {
    var deferred = Q.defer();

    kanbanDemandController.findOneGiveKanbanDemand(item, wareHouseId, function (err, records) {
        if (err) {
            deferred.reject(err);
            return;
        }
        if (records.length === 0) {
            deferred.resolve([]);
            return;
        }
        var results = [],
            batches = [];
        _.forEach(records, function (record) {
            batches.push(queryDemandDetail(item, record, results));
        });
        Q.all(batches).then(function () {
            deferred.resolve(results);
        }, function (err) {
            deferred.reject(err);
        });
    });

    return deferred.promise;
}

function queryDemandDetail (itemMaterObj, kanbanDemand, results) {
    var deferred = Q.defer();

    var _stockQty = 0;
    rcvRecordController.queryStockQty(itemMaterObj.ItemMaster).then(function (stockQty) {
        _stockQty = stockQty;
        return querydepartmentName(kanbanDemand.DemandDepartment);
    }).then(function (resultDepartment) {
        results.push({
            CreatedOn: kanbanDemand.CreatedOn,
            ItemMasterCode: kanbanDemand.ItemMaster.Code,
            ItemMasterName: kanbanDemand.ItemMaster.Name,
            DescSeg1: itemMaterObj.DescSeg1,
            DescSeg2: itemMaterObj.DescSeg2,
            DemandQty: kanbanDemand.TotalDemandQty - kanbanDemand.TotalReceiveQty,
            NeedQty: kanbanDemand.TotalDemandQty - kanbanDemand.TotalReceiveQty - _stockQty,
            RcvQty: itemMaterObj.Num,
            TotalDemandQty: kanbanDemand.TotalDemandQty,
            TotalStockQty: _stockQty,
            TotalReceiveQty: kanbanDemand.TotalReceiveQty,
            DemandDepartment: resultDepartment.Name
        });
        deferred.resolve();
    }).catch(function (err) {
        deferred.resolve();
    });

    return deferred.promise;
}

//通过部门id查询部门名称的方法
function querydepartmentName(DemandDepartment) {
    var deferred = Q.defer();
    var data = {};
    departmentController.findDepartmentById(DemandDepartment, function (departmentErr, departmentResult) {
        if (departmentErr) {
            deferred.reject(err);
        } else {
            if (departmentResult) {
                data = {
                    Name: departmentResult.Name
                };
                deferred.resolve(data);
            }
        }
    });
    return deferred.promise;
}


// //通过（物料+尺寸+外观）和仓库id查询 备货看板需求表中数据
// function queryGiveKanbanDemand(item, wareHouseId) {
//     var deferred = Q.defer();
//     var data = {};
//     kanbanDemandController.findOneGiveKanbanDemand(item, wareHouseId, function (err, result) {
//         if (err) {
//             deferred.reject(err);
//         } else {
//             if (result) {
//                 console.log(result);

//                 departmentController.findDepartmentById(result.DemandDepartment, function (departmentErr, departmentResult) {
//                     if (departmentErr) {
//                         deferred.reject(err);
//                     } else {
//                         if (departmentResult) {
//                             data = {
//                                 CreatedOn: result.CreatedOn,
//                                 ItemMasterCode: result.ItemMaster.Code,
//                                 ItemMasterName: result.ItemMaster.Name,
//                                 DescSeg1: item.DescSeg1,
//                                 DescSeg2: item.DescSeg2,
//                                 DemandQty: result.TotalDemandQty - result.TotalReceiveQty,
//                                 NeedQty: result.TotalDemandQty - result.TotalStockQty,
//                                 RcvQty: item.Num,
//                                 TotalDemandQty: result.TotalDemandQty,
//                                 TotalStockQty: result.TotalStockQty,
//                                 TotalReceiveQty: result.TotalReceiveQty,
//                                 DemandDepartment: departmentResult.Name
//                             };
//                             deferred.resolve(data);
//                         }
//                     }


//                 });

//             }

//         }
//     });
//     return deferred.promise;
// }

//获取上游看板需求
exports.GetUpStreamKanban = function (req, res) {
    var parameter = req.body.Parameter,
        userId = parameter.userId;
    getConnectArea(userId, true).then(function (connectArea) {
        if (!connectArea) {
            res.json({
                Data: null,
                Error: "该用户下没有对应的交接区，请添加相应的交接区信息。"
            });
            return;
        }
        Q.all([
            getRvRecordsByConnectArea(connectArea._id),
            getKanbanDemand({
                ConnectArea: connectArea._id,
                $where: "this.TotalDemandQty - this.TotalStockQty > 0"
            })
        ]).spread(function () {
            if (arguments.length < 2) {
                res.json({
                    Data: null,
                    Error: "通过交接区ID未查到入库记录或者没有满足的看板需求记录."
                });
                return;
            }
            var rvRecords = arguments[0],
                demands = arguments[1],
                kanban = [];
            _.forEach(rvRecords, function (rvRecord) {
                _.forEach(demands, function (demand) {
                    if (rvRecord._id.toString() == demand.MO.toString()) {
                        kanban.push({
                            Priority: demand.Priority == undefined ? 0 : demand.Priority,
                            NOLotNumber: rvRecord.value.barcode.MOLotNumber == undefined ? '' : rvRecord.value.barcode.MOLotNumber,
                            ItemMasterCode: rvRecord.value.barcode.ItemMasterCode == undefined ? '' : rvRecord.value.barcode.ItemMasterCode,
                            ItemMasterName: rvRecord.value.barcode.ItemMasterName == undefined ? '' : rvRecord.value.barcode.ItemMasterName,
                            TotalDemandQty: demand.TotalDemandQty == undefined ? 0 : demand.TotalDemandQty,
                            TotalNeedQty: (demand.TotalDemandQty - demand.TotalStockQty) == undefined ? 0 : (demand.TotalDemandQty - demand.TotalStockQty),
                            RcvQty: rvRecord.value.RcvQty == undefined ? 0 : rvRecord.value.RcvQty,
                            TotalStockQty: demand.TotalStockQty == undefined ? 0 : demand.TotalStockQty,
                            TotalReceiveQty: demand.TotalReceiveQty == undefined ? 0 : demand.TotalReceiveQty
                        });
                    }
                });
            });
            res.json({
                Data: kanban,
                Error: null
            });
        });
    });

};

//获取下游看板需求
exports.GetDownStreamKanban = function (req, res) {
    var parameter = req.body.Parameter,
        userId = parameter.userId;
    //入库记录(批次(工单)-库存)
    getConnectArea(userId, false).then(function (connectArea) {
        if (!connectArea) {
            res.json({
                Data: null,
                Error: "该用户下没有对应的交接区，请添加相应的交接区信息。"
            });
            return;
        }
        Q.all([
            getRvRecordsByConnectArea(connectArea._id),
            getKanbanDemand({
                ConnectArea: connectArea._id,
                $where: "this.TotalDemandQty - this.TotalReceiveQty > 0"
            })
        ]).spread(function () {
            if (arguments.length < 2) {
                res.json({
                    Data: null,
                    Error: "通过交接区ID未查到入库记录或者没有满足的看板需求记录."
                });
                return;
            }
            var rvRecords = arguments[0],
                demands = arguments[1],
                kanban = [];
            _.forEach(rvRecords, function (rvRecord) {
                _.forEach(demands, function (demand) {
                    if (rvRecord._id.toString() == demand.MO.toString()) {
                        kanban.push({
                            Priority: demand.Priority == undefined ? 0 : demand.Priority,
                            NOLotNumber: rvRecord.value.barcode.MOLotNumber == undefined ? '' : rvRecord.value.barcode.MOLotNumber,
                            ItemMasterCode: rvRecord.value.barcode.ItemMasterCode == undefined ? '' : rvRecord.value.barcode.ItemMasterCode,
                            ItemMasterName: rvRecord.value.barcode.ItemMasterName == undefined ? '' : rvRecord.value.barcode.ItemMasterName,
                            RcvQty: rvRecord.value.RcvQty == undefined ? 0 : rvRecord.value.RcvQty,
                            TotalReceiveQty: demand.TotalReceiveQty == undefined ? 0 : demand.TotalReceiveQty,
                            NeedDeliveryQty: (demand.TotalDemandQty - demand.TotalReceiveQty) == undefined ? 0 : (demand.TotalDemandQty - demand.TotalReceiveQty)
                        });
                    }
                });
            });
            res.json({
                Data: kanban,
                Error: null
            });
        }, function (err) {
            res.json({
                Data: null,
                Error: err
            });
        });
    });
};

/**
 * 交接检查交接确认获取看板需求信息
 * jiadx
 */
exports.getKanBanDemandInfo = function (req, res) {
    var parameter = req.body.Parameter,
        demandDepartment = parameter.demandDepartment;
    kanbanDemandController.queryDemandByDepartment(demandDepartment, function (err, records) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            res.json({
                Data: records,
                Error: null
            });
        }
    });
};

//获取所有部门
exports.getAllDepartment = function (req, res) {
    var parameter = req.body.Parameter,
        wareHouseId = parameter.wareHouseId,
        condition;

    if (!wareHouseId) {
        condition = {};
    } else {

        condition = {WareHouse: wareHouseId};
    }
    kanbanDemandController.queryDemandByWareHouse(condition, function (err, records) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            res.json({
                Data: records,
                Error: null
            });
        }
    });
};

//查找到所有仓库
exports.getAllWareHouse = function (req, res) {
    connectAreaController.getAllWareHouse(function (err, result) {
        // console.log("getBarcodeData-------------"+result);
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            if (result == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询仓库失败';
                newErr.message = '未找到对应的仓库！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            } else {
                // //向所有连接发送消息
                // SocketIo.emit("57cea04501cb5c06e86f102b", 1); //data: 任何类型都行

                res.json({
                    Data: result,
                    Error: null
                });
            }
        }
    });

};

//通过配送记录查找超市
exports.getWareHouseByContainer = function (req, res) {
    var parameter = req.body.Parameter,
        containerId = parameter.containerId;
    DeliveryRecordController.queryWareHouseByContainer(containerId, function (err, record) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
            return;
        }
        res.json({
            Data: record || {},
            Error: null
        });
    });
};

//递归查找部门对应的仓库
exports.getWareHouseByDepartment = function (req, res) {
    var parameter = req.body.Parameter,
        departmentId = parameter.departmentId;
    connectAreaController.findByDepartmentDeep(departmentId).then(function (data) {
        res.json({
            Data: data,
            Error: null
        });
    }, function (err) {
        res.json({
            Data: null,
            Error: err
        });
    });
};

//获取容器
exports.getContainer = function (req, res) {
    var parameter = req.body.Parameter,
        entityId = parameter.entityId;
    ContainerController.getContainerById(entityId, function (err, record) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            res.json({
                Data: record,
                Error: null
            });
        }
    });
};

//交接区检货UdpatePIckUpQty,确认服务
exports.PIckUp = function (req, res) {
    var parameter = req.body.Parameter,
        userId = parameter.userId,
        wareHouse = parameter.wareHouse,
        validBarcodeList = parameter.validBarcodeList,
        containerId = parameter.containerId,
        departmentId = parameter.departmentId;

    groupFromBarcodeMaster(validBarcodeList).then(function (results) {
        var groupResults = results;
        if (!groupResults) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '主档分组失败';
            res.json({
                Data: null,
                Error: newErr
            });
            return;
        }

        updateRcvRecord('update', validBarcodeList, containerId).then(function (records) {
            var deliveryRecord = [];
            deliveryRecord.push({
                WareHouse: wareHouse._id,
                DemandDepartment: departmentId,
                Container: containerId,
                Status: 0,
                Qty: validBarcodeList.length,
                //ReadyTime: new Date(),
                StockPerson: userId,
                RowStatus: PublicEnum.RowStatus.Insert
            });
            var taskArr = [];
            _.forEach(groupResults, function (result) {
                taskArr.push(updateKanbanInfo('pick', {
                    WareHouse: wareHouse._id,
                    DemandDepartment: departmentId,
                    ItemMaster: result._id.ItemMaster,
                    DescSeg1: result._id.DescSeg1 ? result._id.DescSeg1 : '',
                    DescSeg2: result._id.DescSeg2 ? result._id.DescSeg2 : ''
                }, result.value.count));
            });
            taskArr.push(BatchSaveByTran([
                {EntityName: 'RcvRecord', Records: records},
                {EntityName: 'DeliveryRecord', Records: deliveryRecord}
            ]));

            Q.all(taskArr).then(function (taskRecord) {
                res.json({
                    Data: taskRecord,
                    Error: null
                });
            }, function (err) {
                res.json({
                    Data: null,
                    Error: err
                });
            });
        }, function (err) {
            res.json({
                Data: null,
                Error: err
            });
        });
    });

};

//交接区收货UpdateArrivedQty,确认服务
exports.Arrived = function (req, res) {
    var parameter = req.body.Parameter,
        userId = parameter.userId,
        TerminalId = parameter.TerminalId,
        TerminalName = parameter.TerminalName,
        WorkId = parameter.WorkId,
        WorkName = parameter.WorkName,
        WorkLocationId = parameter.WorkLocationId,
        WorkLocationName = parameter.WorkLocationName,
        validBarcodeList = parameter.validBarcodeList,
        inValidBarcodeList = parameter.inValidBarcodeList,
        containerId = parameter.containerId,
        wareHouse = parameter.wareHouse,
        departmentId = parameter.departmentId;

    streamValidation(TerminalId, TerminalName, WorkId, WorkName, WorkLocationId, WorkLocationName, userId, validBarcodeList)
        .then(function (romoteData) {
            var rcvRecords = romoteData.rcvRecords,
                bizRecords = romoteData.bizRecords;
            Q.all([
                groupFromBarcodeMaster(validBarcodeList),
                updateRcvRecord('del', validBarcodeList, containerId),
                updateRcvRecord('update', inValidBarcodeList, ''),
                updateDeliveryRecord(containerId, validBarcodeList, userId)
            ]).then(function (results) {
                var groupResults = results[0],
                    delRcvRecords = results[1],
                    updateRcvRecords = results[2],
                    deliveryRecord = results[3],
                    taskArr = [];
                if (!groupResults) {
                    var newErr = new Error();
                    newErr.leval = 9;
                    newErr.title = '查询错误';
                    newErr.message = '仓库查询或者主档分组失败';
                    res.json({
                        Data: null,
                        Error: newErr
                    });
                    return;
                }

                _.forEach(groupResults, function (result) {
                    taskArr.push(updateKanbanInfo('arrived', {
                        WareHouse: wareHouse._id,
                        DemandDepartment: departmentId,
                        ItemMaster: result._id.ItemMaster,
                        DescSeg1: result._id.DescSeg1 ? result._id.DescSeg1 : '',
                        DescSeg2: result._id.DescSeg2 ? result._id.DescSeg2 : ''
                    }, result.value.count));
                });

                taskArr.push(BatchSaveByTran([
                    {EntityName: 'RcvRecord', Records: delRcvRecords},
                    {EntityName: 'RcvRecord', Records: updateRcvRecords},
                    {EntityName: 'DeliveryRecord', Records: deliveryRecord}
                ]));

                Q.all(taskArr).then(function () {
                    writeBizRecord(bizRecords).then(function (ress) {
                        var arr = [];
                        _.forEach(ress[0].Insert, function (re) {
                            arr.push(re._doc);
                        });
                        var taskThree = [];
                        taskThree.push(addStockQty(departmentId, rcvRecords));
                        taskThree.push(updateBarcodeMasterByValue(arr));

                        Q.all(taskThree).then(function () {
                            res.json({
                                Data: {},
                                Error: null
                            });
                        }, function (err) {
                            res.json({
                                Data: null,
                                Error: err
                            });
                        });

                    }, function (err) {
                        res.json({
                            Data: null,
                            Error: err
                        });
                    });

                }, function (err) {
                    res.json({
                        Data: null,
                        Error: err
                    });
                });
            });
        }, function (err) {
            res.json({
                Data: null,
                Error: err
            });
        });
};

//交接检查是获取球拍的检查状态、重复扫描的合规性
exports.getBarcodeMasterInfo = function (req, res) {
    var parameter = req.body.Parameter,
        Barcode = parameter.Barcode;
    var entityRcvRecord = entityCollection.getEntity("RcvRecord"),
        entityBarcodeMaster = entityCollection.getEntity("BarcodeMaster");
    //现根据芯片ID检查入库记录，做重复扫描的合规性检查
    entityRcvRecord.findOne({Barcode: Barcode}, null, function (err, record) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
            return;
        }
        if (!record) {
            res.json({
                Data: "此球拍没有做入库或这是重复扫描",
                Error: null
            });
        } else {
            //接收芯片对应的条码主档
            entityBarcodeMaster.findOne({Barcode: Barcode}, null, function (err, record) {
                if (err) {
                    res.json({
                        Data: null,
                        Error: err
                    });
                    return;
                }
                res.json({
                    Data: record,
                    Error: null
                });
            });
        }
    });
};

//通过用户ID获取交接区信息,flag == true(上游)，flag == false(下游)
function getConnectArea(userId, flag) {
    var deferred = Q.defer();
    var userModel = mongoose.model('User');
    //通过用户ID获取部门
    userModel.findOne({_id: userId}, {Department: 1}).exec(function (err, record) {
        if (err) {
            deferred.reject(err);
        }

        if (!record) {
            deferred.reject("用户对应部门为空");
        }
        var queryCondition = {};
        if (flag) {
            queryCondition = {UpDepartment: record.Department};
        } else {
            queryCondition = {DownDepartment: record.Department};
        }
        //通过用户部门获取交界区
        var entity = entityCollection.getEntity("WareHouse");
        entity.findOne(queryCondition, null, function (err, result) {
            if (err) {
                deferred.reject(err);
            } else {
                deferred.resolve(result);
            }
        });
    });
    return deferred.promise;
}

//根据芯片ID(Barcode)，分组key,获取条码主档[key,value]
function queryByBarcodeAndGroupByMo(key, barcodeList) {
    var deferred = Q.defer();
    var entityBarcodeMaster = entityCollection.getEntity("BarcodeMaster");
    entityBarcodeMaster.aggregateCount(key, {Barcode: {$in: barcodeList}}, function (err, data) {
        if (err) {
            deferred.reject(err);
        }
        deferred.resolve(data);
    });
    return deferred.promise;
}

//根据交界区ID取得看板
function getKanbanDemand(condition) {
    var deferred = Q.defer();
    var entity = entityCollection.getEntity("KanbanDemand");
    entity.find(condition, null, null, function (err, results) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(results);
        }
    });
    return deferred.promise;
}

//根据交接区ID获取入库记录
function getRvRecordsByConnectArea(connectAreaId) {
    var deferred = Q.defer();
    var entity = entityCollection.getEntity("RcvRecord");

    var barcodeMap = function () {
        emit(this.BusinessDocID, {barcode: this.BarcodeMaster, RcvQty: this.RcvQty});
    };

    var reduce = function (key, values) {
        return {barcode: this.BarcodeMaster, RcvQty: Array.sum(values.RcvQty)}
    };

    var query = {
        //connectAreaId: connectAreaId,
        //Location: null
    };

    var option = {
        map: barcodeMap,
        reduce: reduce,
        query: query
    };

    entity.mapReduce(option, function (err, results) {
        var barcodeModel = mongoose.model('BarcodeMaster');
        barcodeModel.populate(results, {path: 'value.barcode'}, function (err, resultsBarcodes) {
            deferred.resolve(resultsBarcodes);
        });
    });

    return deferred.promise;
}

//根据芯片ID(Barcode)获取入库记录
function getRcvRecordsByBarcode(barcodeList) {
    var deferred = Q.defer();
    var entity = entityCollection.getEntity("RcvRecord");
    entity.find({Barcode: {$in: [barcodeList]}}, null, null, function (err, records) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(records);
        }
    });
    return deferred.promise;
}

//获取看板更新数据
function updateKanbanByCondition(flg, condition, moAndNum) {
    var deferred = Q.defer();
    kanbanDemandController.findRecordsByCondition(condition, function (err, records) {
        if (err) {
            deferred.reject(err);
        } else {
            _.forEach(records, function (record) {
                if (moAndNum.hasOwnProperty(record.MO._id)) {
                    if (flg === 'pIck') {
                        record.TotalStockQty += moAndNum[record.MO._id];
                    } else {
                        record.TotalReceiveQty += moAndNum[record.MO._id];
                    }

                    record.RowStatus = PublicEnum.RowStatus.Modify;
                }
            });
            deferred.resolve(records);
        }
    });
    return deferred.promise;
}

//获取入库记录更新数据
function updateRcvRecord(flg, Barcodes, containerId) {
    var deferred = Q.defer();
    barcodeMasterController.findBarcodeMasters(Barcodes, false)
        .then(function (BarcodeList) {
            var arrList = [];
            _.forEach(BarcodeList, function (bar) {
                arrList.push(bar._id);
            });
            rcvRecordController.queryByCondition({
                BarcodeMaster: {$in: arrList}
            }, function (err, records) {
                if (err) {
                    deferred.reject(err);
                } else {
                    // if (!records || records.length !== arrList.length) {
                    //     var ar = [11];
                    //     deferred.resolve(ar);
                    //     return;
                    // }
                    _.forEach(records, function (record) {
                        if (flg === 'update') {
                            record.RowStatus = PublicEnum.RowStatus.Modify;
                        } else if (flg === 'del') {
                            record.RowStatus = PublicEnum.RowStatus.Delete;
                        } else {

                        }
                        record.Container = containerId;
                    });
                    deferred.resolve(records);
                }
            });
        });

    return deferred.promise;
}

function updateDeliveryRecord(containerId, validBarcodeList, userId) {
    var deferred = Q.defer();
    var deliveryArr = [];
    DeliveryRecordController.queryByCondition({
        Container: containerId,
        Status: { $ne: 2 }
    }, function (err, record) {
        if (err) {
            deferred.reject(err);
        } else {
            deliveryArr.push({
                _id: record._id,
                RowStatus: PublicEnum.RowStatus.Modify,
                Status: 2,
                ReceiveQty: validBarcodeList.length,
                ReadyTime: new Date(),
                StockPerson: userId
            });
            deferred.resolve(deliveryArr);
        }
    });
    return deferred.promise;
}

//通过配送记录限制交接检查重复提交
function getDeliveryRecord(containerId, wareHouseId) {
    var deferred = Q.defer();
    DeliveryRecordController.queryByCondition({
        Container: containerId,
        WareHouse: wareHouseId,
        $or: [{ReceiveQty: {$exists: false}}, {ReceiveQty: 0}]
    }, function (err, record) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(record);
        }
    });
    return deferred.promise;
}

/**
 * 获取仓库
 * @returns {*|promise}
 */
function getWareHouseInfoByDepartmentId(departmentId) {
    var deferred = Q.defer();
    connectAreaController.getWareHouseInfoByDepartmentId(departmentId, function (err, wareHouseInfo) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(wareHouseInfo);
        }
    });
    return deferred.promise;
}
/**
 * 对主档分组
 * @param barcodeList
 * @returns {*|promise}
 */
function groupFromBarcodeMaster(barcodeList) {
    var deferred = Q.defer();
    barcodeMasterController.groupFromBarcodeMaster(barcodeList, function (err, result) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(result);
        }
    });
    return deferred.promise;
}

/**
 *
 * @param flg
 * @param condition
 * @param num
 * @returns {*}
 */
function updateKanbanInfo(flg, condition, num) {
    var deferred = Q.defer();
    kanbanDemandController.updateByCondition(flg, condition, num, function (err, record) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(record);
        }
    });
    return deferred.promise;
}

/**
 * 更新相应的表
 * @param array
 * @returns {*|promise}
 * @constructor
 */
function BatchSaveByTran(array) {
    var deferred = Q.defer();
    Transaction.BatchSaveByTran(array, function (err, result) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(result);
        }
    });
    return deferred.promise;

}

/**
 * 流水校验
 * @param TerminalId
 * @param TerminalName
 * @param WorkId
 * @param WorkName
 * @param WorkLocationId
 * @param WorkLocationName
 * @param userId
 * @param barcodeList
 * @returns {*|promise}
 */
function streamValidation(TerminalId, TerminalName, WorkId, WorkName, WorkLocationId, WorkLocationName, userId, barcodeList) {
    var deferred = Q.defer();
    var bizRecords = [],
        taskBizRecords = [],
        rcvRecords = [],
        operation = {};
    barcodeMasterController.findBarcodeMasters(barcodeList).then(function (records) {
        _.forEach(records, function (record) {
            var bizRecord = {
                BarcodeMaster: record._id,
                CollectDateTime: Date.now(),
                Terminal: TerminalId,
                TerminalName: TerminalName,
                Work: WorkId,
                WorkName: WorkName,
                WorkLocation: WorkLocationId,
                WorkLocationName: WorkLocationName,
                Users: [userId]
            };

            var rcvRecord = {
                BarcodeMaster: record._id,
                Barcode: record.Barcode,
                ItemMaster: record.ItemMaster ? record.ItemMaster._id : '',
                DescSeg1: record.DescSeg1,
                DescSeg2: record.DescSeg2,
                BusinessDocID: record.MO ? record.MO._id : '',
                RcvUser: (bizRecord.Users && bizRecord.Users.length > 0) ? bizRecord.Users[0] : null,
                //RcvOperation: operation._id,
                BizRecord: bizRecord.BizRecord,
                //WareHouse: wareHouse._id,
                RcvDateTime: bizRecord.CollectDateTime
            };

            taskBizRecords.push(queryOperation(record.ItemMaster, WorkId).then(function (operation) {

                bizRecords.push(_.merge(bizRecord, {
                    Operation: operation._id, OperationName: operation.Name
                }));
                rcvRecords.push(_.merge(rcvRecord, {RcvOperation: operation._id, OperationFlg: operation}));
                //return barcodeMasterController.streamValidation(record, operation);
            }));
        });
        Q.all(taskBizRecords).then(function () {
            deferred.resolve({
                bizRecords: bizRecords,
                rcvRecords: rcvRecords
            });
        }, function (err) {
            deferred.reject(err);
        });
    }, function (err) {
        deferred.reject(err);
    });
    return deferred.promise;
}

/**
 * 通过物料和作业查找工序
 * @param itemMaster
 * @param work
 * @returns {*|promise}
 */
function queryOperation(itemMaster, work) {
    var deferred = Q.defer();

    operationController.findByItemMasterAndWork(itemMaster, work, function (err, result) {
        if (err) {
            deferred.reject(err);
            return;
        }
        if (!result) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '非法数据';
            newErr.message = '没有找到对应的工序';
            deferred.reject(newErr);
            return;
        }
        deferred.resolve(result);
    });

    return deferred.promise;
}

/**
 * 写入流水 -- 批量
 * @param bizRecords
 * @returns {*|promise}
 */
function writeBizRecord(bizRecords) {
    var deferred = Q.defer();
    bizRecordController.addBizRecords(bizRecords, function (err, result) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(result);
        }
    });
    return deferred.promise;
}

function addStockQty(departmentId, rcvRecords) {
    var deferred = Q.defer();

    wareHouseController.findByDepartmentDeep(departmentId).then(function (wareHouse) {
        if (!wareHouse) {
            deferred.resolve({});
            return;
        }
        var finalRecords = [];
        _.forEach(rcvRecords, function (rcvRecord) {
            if (rcvRecord.OperationFlg && rcvRecord.OperationFlg.IsStoragePoint) {
                finalRecords.push(_.merge(rcvRecord, {WareHouse: wareHouse._id}));
            }
        });
        if (finalRecords.length === 0) {
            deferred.resolve({});
        } else {
            rcvRecordController.addStockQty(finalRecords).then(function (data) {
                deferred.resolve(data);
            }, function (err) {
                deferred.reject(err);
            });
        }
    }, function () {
        deferred.resolve({});
    });

    return deferred.promise;
}

function updateBarcodeMasterByValue(bizRecords) {
    var deferred = Q.defer();
    var records = [];
    _.forEach(bizRecords, function (bizRecord) {
        var record = {
            _id: bizRecord.BarcodeMaster,
            Operation: bizRecord.Operation,
            OperationName: bizRecord.OperationName,
            Work: bizRecord.Work,
            WorkName: bizRecord.WorkName,
            WorkLocation: bizRecord.WorkLocation,
            WorkLocationName: bizRecord.WorkLocationName,
            Users: bizRecord.Users,
            BizRecord: bizRecord._id,
            RowStatus: PublicEnum.RowStatus.Modify
        };
        records.push(record);
    });
    Transaction.BatchSaveByTran([{EntityName: 'BarcodeMaster', Records: records}], function (err, result) {
        if (err) {
            deferred.reject(err);
            return;
        }
        deferred.resolve(result);
    });
    return deferred.promise;
}
